package com.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.web.savedrequest.DefaultSavedRequest;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.Map;

import static com.authentication.common.Constant.SELECT_SCOPE_URL;
import static com.config.AuthorizationServerConfig.OAUTH_2_AUTHORIZATION_SERVER;

@Controller
public class ScopeController {

    private final RequestCache selectingScopesRequestCache;

    private final RegisteredClientRepository registeredClientRepository;

    public ScopeController(RequestCache selectingScopesRequestCache, RegisteredClientRepository registeredClientRepository) {
        this.selectingScopesRequestCache = selectingScopesRequestCache;
        this.registeredClientRepository = registeredClientRepository;
    }

    @GetMapping(SELECT_SCOPE_URL)
    public ModelAndView selectScopes(HttpServletRequest request, HttpServletResponse response) {

        SavedRequest authorizationRequest = selectingScopesRequestCache.getRequest(request, response);


        UriComponents url = UriComponentsBuilder.fromHttpUrl(authorizationRequest.getRedirectUrl()).build();
        MultiValueMap<String, String> queryParams = url.getQueryParams();

        String clientId = queryParams.getFirst("client_id");

        RegisteredClient registeredClient = registeredClientRepository.findByClientId(clientId);



        return new ModelAndView("/authorizationDecision")
                .addObject("clientName",registeredClient.getClientName())
                .addObject("scopes",registeredClient.getScopes())
                .addObject("authorizationUri",OAUTH_2_AUTHORIZATION_SERVER)
                .addObject("requestScopes",queryParams.get("scope"));
    }

}
